package com.kdtech.analyse.video;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.analyse.AnalyseNews;

/**
 * 嘉定电视台
 * @author Administrator
 * abc
 */
public class JdtvAnalyse implements AnalyseNews{
	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://www.jdtv.sh.cn/Item/[0-9]+.aspx"
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta video = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		video.setUrl(url);
		String title = null;
		String desc = null;
		Long date = null;
		String dateStr = null;
		Document doc = Jsoup.parse(htmltxt);
		title = doc.select("div.newscontent >h1").text();

			desc = doc.select("div.newscontent div.all div#acright").text();
			dateStr =doc.select("div.newscontent >p.topbott").text();
			date = DateUtils.matchDate(dateStr);
			video.setTitle(StringUtils.trimSpace(title));
			video.setContent(desc);
			video.setDate(date);
			String updateTemp =doc.select("div.newscontent >p.topbott >script").attr("src");
			if(updateTemp.length() > 0){

				video.setUpdateUrl("http://www."+urlMeta.getDomain()+updateTemp);
			}
			NewsMeta update = Update(video);
			if (update!=null) {
				video.setClickNum(update.getClickNum());
			}
			return video;
	}
	

	
	public NewsMeta Update(NewsMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if(updateUrl!=null){
				UrlMeta responseToURL = CrawlHTML.responseToURL(updateUrl);
				if(responseToURL!=null){
					String html = responseToURL.getHtml();
					if(html!=null){
						int index = html.indexOf("('");
						int index2 = html.indexOf("')");
						String click = html.substring(index+2,index2).trim();
						Integer clicknum = 0;
						try {
							clicknum = Integer.valueOf(click);
						} catch (Exception e) {
							// TODO: handle exception
						}
						meta.setClickNum(clicknum);
						return meta;
					}
				}
			}
		}
		return null;
	}
	
}
